package cn.supermarket.ex.handler;

import cn.supermarket.ex.ServiceException;
import cn.supermarket.web.JsonResult;
import cn.supermarket.web.State;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(ServiceException.class)
    public JsonResult<Void> handlerServerException(ServiceException serviceException) {
        return JsonResult.fail(serviceException.getState(), serviceException.getMessage());
    }

    @ExceptionHandler(BindException.class)
    public JsonResult<Void> handleBindException(BindException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        StringBuilder fieldEr = new StringBuilder();
        for (FieldError fieldError : fieldErrors) {
            fieldEr.append(";");
            fieldEr.append(fieldError.getField());
        }
        return JsonResult.fail(State.ERR_BAD_REQUEST,fieldEr.toString());
    }
}
